import 'dart:async';

import 'package:flutter/material.dart';

class HorsepowerWidget extends StatelessWidget {
  final int max;
  final int current;
  final ValueNotifier<int> repaint = ValueNotifier<int>(0);

  final Size size;

  HorsepowerWidget({
    super.key,
    this.max = 20,
    this.current = 10,
    required this.size,
  });

  @override
  Widget build(BuildContext context) {
    debugPrint('Horsepower build == $size');
    Timer.periodic(const Duration(milliseconds: 80), (timer) {
      if (repaint.value == current) {
        repaint.value = current;
        timer.cancel();
      } else {
        if (repaint.value > current) {
          repaint.value--;
        } else {
          repaint.value++;
        }
      }
    });
    return RepaintBoundary(
      child: CustomPaint(
        size: size,
        painter: Horsepower(max: max, current: current, vn: repaint),
      ),
    );
  }
}

class Horsepower extends CustomPainter {
  int max;
  int current;
  List<Color> colors;
  ValueNotifier<int> vn;

  Horsepower({
    this.current = 0,
    this.max = 10,
    this.colors = const [Colors.red, Colors.blue],
    required this.vn,
  }) : super(repaint: vn) {
    debugPrint('Horsepower =======');
  }

  @override
  void paint(Canvas canvas, Size size) {
    debugPrint('Horsepower paint == $size');
    var rect = Rect.fromLTWH(0, 0, size.width, size.height);
    var paint = Paint()
      ..isAntiAlias = true
      ..style = PaintingStyle.fill //填充
      ..color = const Color(0xFFDCC48C)
      ..shader = LinearGradient(
        colors: colors,
      ).createShader(rect);
    canvas.drawRect(rect, paint);
    var itemWidth = size.width / (max * 2 - 1);

    for (var i = 0; i < max * 2 - 1; ++i) {
      if (i >= vn.value * 2 - 1 || i % 2 != 0) {
        var paint2 = Paint()
          ..isAntiAlias = true
          ..style = PaintingStyle.fill
          ..color = i % 2 != 0 ? Colors.white : Colors.grey
          ..blendMode = BlendMode.src;
        canvas.drawRect(Rect.fromLTWH(i * itemWidth, 0, itemWidth, size.height), paint2);
      }
    }
  }

  @override
  bool shouldRepaint(Horsepower oldDelegate) {
    debugPrint('Horsepower shouldRepaint == ${this != oldDelegate}');
    vn.value = oldDelegate.vn.value;
    return this != oldDelegate;
  }
}
